import 'dart:async';

import 'package:color_dart/color_dart.dart';
import 'package:color_dart/rgba_color.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertz/components/a_button/index.dart';
import 'package:fluttertz/components/a_dialog/a_dialog.dart';
import 'package:fluttertz/components/a_row/a_row.dart';
import 'package:fluttertz/jsonserialize/jt_list/data.dart';
import 'package:fluttertz/utils/global.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class Home extends StatefulWidget {
  static _HomeState _homeState;

  Home() {
    _homeState = _HomeState();
  }

  getAppBar() => _homeState.createAppBar();

  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  double bottom = G.screenPadding().bottom;

  AppBar createAppBar() {
    return null;
  }

  static double _nestedScrollOffet = 0;
  final ScrollController _nestedScrollController = new ScrollController();

  JtList _jtList = null;
  int _jtListLen = 0;

  @override
  void initState() {
    _nestedScrollController.addListener(() {
      setState(() {
        _nestedScrollOffet = _nestedScrollController.offset;
      });
    });

    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      _init(context);
      _num++;
    });

    super.initState();

  }

  int _num = 0;
  Timer _timer = null;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  bool _isloading = false;

  _init(BuildContext context) async {
    if (G.user.data == null || _isloading) {
      return;
    }

    _isloading = true;

    print('$_num ' + DateTime.now().toString());

    try {
      int adminid = G.user.data.adminid;

      Response response;
      Dio dio = Dio();
      response = await dio.post("https://aps.acciot.com.tw/api/taizhu/jtlist",
          queryParameters: {"adminid": adminid});

      if (response == null) {
        _isloading = false;
        return G.toast('獲取機台列表失敗！');
      }

      _jtList = JtList.fromJson(response.data);
      _jtListLen = _jtList.data.length;

      // 在 setState 之前先判断一下该 State 是否已经被释放,否则 setState () called after dispose()
      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      print(e);
    }

    _isloading = false;
  }

  @override
  Widget build(BuildContext context) {
    // ScreenUtil.init(context,
    //     designSize: Size(750, 1334), allowFontScaling: false);
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: AssetImage("lib/assets/images/tz/bg.png"),
          fit: BoxFit.cover,
        )),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: customAppbar(
            title: '機台',
            // context: null, //null不显示返回按钮 但还是响应
          ),
          body: Stack(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 0, right: 0),
                child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    return jtrow(index);
                  },
                  // itemExtent: 100.0, //确定每一个item的高度 会让item加载更加高效
                  itemCount: _jtListLen,
                ),
              ),
            ],
          ),
        ));
  }

  Widget row(String title,
      {double fontSize = 13, FontWeight fontWeight, Color color}) {
    return Row(
      children: <Widget>[
        Expanded(
          child: Text(
            title,
            style: TextStyle(
                color: color == null ? rgba(166, 166, 166, 1) : color,
                fontSize: fontSize,
                height: 2,
                fontWeight:
                    fontWeight == null ? FontWeight.normal : fontWeight),
          ),
        )
      ],
    );
  }

  Widget jtrow(int index) {
    JtListDatum jtone = _jtList.data[index];
    return ARow(
      onPressed: () {
        G.user.jtinfo = jtone;
        G.pushNamed('/jtinfo');
      },
      height: 152,
      color: hex('#ccfdf6e9'),
      borderRadius: BorderRadius.all(Radius.circular(16.0)),
      border: Border.all(width: 1, color: rgba(242, 242, 242, 1)),
      margin: EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 10),
      leftChild: AButton.normal(
          width: 80,
          height: 80,
          // type: 'warning',
          bgColor: rgba(113, 163, 224, 1),
          borderRadius: BorderRadius.circular(40),
          borderColor: rgba(204, 192, 180, 1),
          onPressed: () {
            //强制消保
            if (jtone.isonline != 1) {
              G.toast('機台已離線!');
            } else {
              String info = "請確認對此機台強制消保[${jtone.name}]?";
              ADialog.confirm(context, content: info, confirmButtonPress: () {
                Future.delayed(Duration.zero, () {
                  doQzxb(context, jtone);
                });
              });
            }
          },
          child: Text(
            '消保',
            style: TextStyle(
                color: rgba(255, 255, 255, 1),
                fontSize: 24,
                fontWeight: FontWeight.bold),
          )),
      centerChild: Container(
        margin: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            row(jtone.name,
                color: rgba(56, 56, 56, 1),
                fontSize: 20,
                fontWeight: FontWeight.bold),
            row("目前累計投幣金額", fontSize: 16),
            row("損益", fontSize: 16),
            row("自動消保", fontSize: 16),
          ],
        ),
      ),
      rightChild: Column(
        children: <Widget>[
          Text(
            jtone.isonline == 1 ? "在線" : "離線",
            textAlign: TextAlign.right,
            style: TextStyle(
                color: jtone.isonline == 1
                    ? rgba(114, 178, 56, 1)
                    : rgba(255, 30, 30, 1),
                fontSize: 18,
                height: 2),
          ),
          Container(
              margin: EdgeInsets.only(top: 10),
              child: Text(
                "${jtone.money}",
                textAlign: TextAlign.right,
                style: TextStyle(color: rgba(255, 30, 30, 1), fontSize: 20),
              )),
          Container(
              margin: EdgeInsets.only(top: 10),
              child: Text(
                "${jtone.shunyi}",
                textAlign: TextAlign.right,
                style: TextStyle(
                    color: jtone.shunyi > 0
                        ? rgba(0, 0, 255, 1)
                        : rgba(255, 30, 30, 1),
                    fontSize: 20),
              )),
          Container(
            child: Switch(
              value: jtone.auto_switch == 1 ? true : false,
              activeColor: Colors.red,
              onChanged: (value) {
                if (jtone.isonline != 1) {
                  G.toast('機台已離線!');
                } else {
                  //自動消保
                  String info = "請確認開啟[${jtone.name}]此機台自動消保?";
                  if (jtone.auto_switch == 1) {
                    info = "請確認關閉[${jtone.name}]此機台自動消保?";
                  }
                  ADialog.confirm(context, content: info,
                      confirmButtonPress: () {
                    Future.delayed(Duration.zero, () {
                      doZdxb(context, jtone);
                    });
                  });
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  doQzxb(BuildContext context, JtListDatum jtone) async {
    G.loading.show(context);
    try {
      Response response;
      Dio dio = Dio();
      response = await dio.post("https://aps.acciot.com.tw/api/taizhu/qzxb",
          queryParameters: {"id": jtone.id});

      if (response == null) {
        G.loading.hide(context);
        return G.toast('網絡無連接！');
      }

      Map<String, dynamic> resCallbackMap = response.data;

      int code = resCallbackMap['code'];
      if (code != 1) {
        G.toast('機台無回應訊息!');
        G.loading.hide(context);
        return null;
      }
      await G.toast('強制消保成功!');

      G.loading.hide(context);
    } catch (e) {
      print(e);
      G.loading.hide(context);
    }
  }

  doZdxb(BuildContext context, JtListDatum jtone) async {
    G.loading.show(context);
    try {
      Response response;
      Dio dio = Dio();
      response = await dio.post("https://aps.acciot.com.tw/api/taizhu/zdxb",
          queryParameters: {"id": jtone.id});

      if (response == null) {
        G.loading.hide(context);
        return G.toast('網絡無連接！');
      }

      Map<String, dynamic> resCallbackMap = response.data;

      int code = resCallbackMap['code'];
      if (code != 1) {
        G.toast('操作失敗!');
        G.loading.hide(context);
        return null;
      }

      if (jtone.auto_switch == 1) {
        jtone.auto_switch = 0;
      } else {
        jtone.auto_switch = 1;
      }

      setState(() {});

      G.loading.hide(context);
      G.toast('操作成功!');
      return null;
    } catch (e) {
      print(e);
      G.loading.hide(context);
    }
  }
}
